package com.activemq.demo.activemq_service.service;

import com.activemq.demo.activemq_service.model.MessageRequest;
import com.activemq.demo.activemq_service.model.MessageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class MessageProducerService {

    private static final Logger logger = LoggerFactory.getLogger(MessageProducerService.class);

    @Value("${app.queue.main:message.queue}")
    private String mainQueue;

    @Autowired
    private JmsTemplate jmsTemplate;

    public MessageResponse sendMessage(MessageRequest messageRequest) {
        String messageId = UUID.randomUUID().toString();
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

        try {
            // 发送消息到队列
            jmsTemplate.convertAndSend(mainQueue, messageRequest.getContent(), message -> {
                message.setStringProperty("messageId", messageId);
                message.setStringProperty("correlationId", messageRequest.getCorrelationId());
                message.setIntProperty("priority", messageRequest.getPriority());
                message.setStringProperty("timestamp", timestamp);
                return message;
            });

            logger.info("消息发送成功 - ID: {}, 内容: {}", messageId, messageRequest.getContent());

            return new MessageResponse(
                messageId,
                "SENT",
                timestamp,
                mainQueue
            );

        } catch (Exception e) {
            logger.error("消息发送失败 - ID: {}, 错误: {}", messageId, e.getMessage(), e);
            return new MessageResponse(
                messageId,
                "FAILED",
                timestamp,
                mainQueue
            );
        }
    }
}